package com.chess.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chess.bean.Room;
import com.chess.service.RoomManager;

@Controller
@Scope("prototype")
public class ChessServlet {
	
	@Autowired
	private RoomManager roomManager;
	
	@RequestMapping(value = { "index"})
	public String page(HttpServletRequest request,HttpServletResponse response, Model model){
		return "index";
	}
	

	@RequestMapping(value = {"chessServlet"})
	public void chessServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Room room=roomManager.enter(request.getParameter("myName"));
		responseOutWithJson(response,room);
	}
	
	/**
	 * 以JSON格式输出
	 * @param response
	 */
	protected void responseOutWithJson(HttpServletResponse response,
			Object responseObject) {
		//将实体对象转换为JSON Object转换
		
		JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(responseJSONObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
